package com.enbatis.mybatisplugs.base;
import com.enbatis.mybatisplugs.toolkit.LoginCacheUtil;
import com.github.pagehelper.Page;
import com.enbatis.mybatisplugs.commons.utils.CodeMsg;
import com.enbatis.mybatisplugs.commons.utils.ResultReturn;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseController {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;

    public BaseController() {
    }

    public Account getAccount(){
        Cookie[] cookies=  request.getCookies();
        for (Cookie cookie:cookies) {
            Account user=LoginCacheUtil.loginUser.get(cookie.getValue());

            if (null!=user){
                return user;
            }
        }
        return null;
    }


    /**
     *
     * @param data 参数
     * @param <T> 泛型
     * @return 对象
     */
    public <T> ResultReturn<T> success(T data){
        return ResultReturn.success(data);
    }


    /**
     *
     * @param data 参数
     * @return 返回值
     */
    public  ResultReturn<Object> failed(CodeMsg data){
        return ResultReturn.error(data);
    }


    public  ResultReturn<Object> failed(String data){
        return ResultReturn.error(data);
    }


    /**
     *
     * @param <T> 泛型
     * @return 泛泛型对象
     */
    protected <T> Page<T> getPage(){
     return   this.setPage(20,true);
    }


    /**
     *
     * @param size 参数
     * @param isOrder 参数
     * @param <T> 泛型
     * @return 返回
     */
    protected <T> Page<T> setPage(int size,Boolean isOrder){

        int currentPage=1;
        String limit=  this.request.getParameter("rows");
        if(StringUtils.isNotBlank(limit)){
            size=Integer.parseInt(limit);
        }

        String currentPageNum=  this.request.getParameter("page");
        if (StringUtils.isNotBlank(currentPageNum)){
            currentPage=Integer.parseInt(currentPageNum);
        }
        String sort = this.request.getParameter("sidx");

        Page<T> page=new Page<>(currentPage,size,true);
        if (StringUtils.isNotBlank(sort)&&null!=isOrder&&isOrder){
            page.setOrderBy(sort);

        }

        return page;

    }
}
